<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>游戏大厅</title>
  <link rel="stylesheet" href="css/conmmon.css">
  <link rel="stylesheet" href="css/game_hall.css">
  <link rel="stylesheet" href="css/login.css">
  <script src="js/jquery.min.js"></script>
</head>
<body>
  <div class="nav">五子棋</div>
  <!-- 整个页面的容器元素 -->
  <div class="container">
    <!-- 这个 div 在 container 中是处于垂直水平居中 -->
    <div>
      <!--展示用户信息-->
      <div id="screen"></div>
      <!--匹配按钮-->
      <div id="match-button" onclick="mate()">开始匹配</div>
    </div>
  </div>
  <script>
    jQuery.ajax({
      url:"/user/getuser",
      type:"POST",
      success: function(result) {
        if(result != null && result.code == 200 && result.data != null){
          let screenDiv = document.querySelector("#screen");
          screenDiv.innerHTML = "玩家：" + result.data.username + " 分数：" + result.data.score
            + "<br> 比赛场数：" + result.data.totalCount + " 获胜场数：" + result.data.winCount
        }else{
          alert("查询用户信息失败，请重试！");
        }
      }

    });

    // 初始化 websocket, 并实现前端匹配逻辑
    let websocketUrl = 'ws://'+ location.host +'/findMatch';
    let websocket = new WebSocket(websocketUrl);
    websocket.onopen = function() {
      console.log("onopen");
    }
    websocket.onclose = function() {
      console.log("onclose");
      
    }
    websocket.onerror = function() {
      console.log("onerror");
    }
    // 监听页面是否关闭，在页面关闭之前手动调用 close 方法
    window.onbeforeunload = function(){
      websocket.close();
    }
    
    websocket.onmessage = function(e) {
      // 处理服务器针对 “开始匹配” / “结束匹配” 的响应
      // 解析得到响应对象，返回的数据是一个 JSON 字符串，解析为 js 对象
      let resp = JSON.parse(e.data);
      // 匹配按钮
      let matchButton = document.querySelector('#match-button');
      if(!resp.ok){
        console.log("游戏大厅中接受到了失败响应！" + resp.reason);
        return;
      }

      if(resp.message == "startMatch"){
        // 开始匹配请求发送成功;
        console.log("进入匹配队列成功！")
        matchButton.innerHTML = '匹配中...(点击停止)';

      } else if (resp.message == 'stopMatch'){
        // 结束匹配请求发送成功
        console.log("离开匹配队列成功！");
        matchButton.innerHTML = '开始匹配';

      } else if (resp.message == 'matchSuccess'){
        // 匹配成功
        console.log("匹配成功！进入游戏房间！");
        location.replace("/game_room.html");

      } else if (resp.message == 'repeatConnection') {
        alert("检测到用户已登录");
        location.replace("/login.html");
      } else {
        console.log("非法响应! message = " + resp.message);
      }
    }

    
    function mate(){
      // 匹配按钮
      let matchButton = document.querySelector('#match-button');
      // 确认 websocket 连接完好
      if(websocket.readyState == websocket.OPEN){
        //连接正常,发送 开始匹配/停止匹配
        if(matchButton.innerHTML == '开始匹配'){
          console.log("开始匹配");
          websocket.send(JSON.stringify({
            message: 'startMatch',
          }));

        }else if(matchButton.innerHTML == '匹配中...(点击停止)'){
          console.log("停止匹配");
          websocket.send(JSON.stringify({
            message:'stopMatch',
          }));
        }

      }else{
        //连接异常
        alert("检测到您当前连接异常！请重新登录！");
        location.replace('/login.html');
      }
    }
    
  </script>
</body>
</html>